import PureNewMachine from '../components/new-machine';
import * as MachineAction from 'actions/machine';
import { getFetchStatus } from 'actions/util';
import { popLayer } from 'actions';
import * as React from 'react';
import * as ReactRedux from 'react-redux';

const mapStateToProps = (state) => {
  return {
    machineSourceFetching: getFetchStatus(state, MachineAction.listAllMachineSources),
    machineSources: state.machineSourceList
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    initFetch() {
      dispatch(MachineAction.listAllMachineSources());
    },
    createMachine(machine) {
      return dispatch(MachineAction.create(machine))
        .then(({ error, payload }) => {
          return error ? Promise.reject(payload) : Promise.resolve(payload);
        });
    },
    closeSelf() {
      dispatch(popLayer());
    }
  };
};

class NewMachine extends React.Component {
  componentDidMount() {
    this.props.initFetch();
  }

  render() {
    return <PureNewMachine {...this.props}/>;
  }
}

export default ReactRedux.connect(mapStateToProps, mapDispatchToProps)(NewMachine);
